import { Context, Next } from 'koa';
import { koaSwagger } from 'koa2-swagger-ui';
import { swaggerSpec, swaggerUiOptions } from '@/config/swagger';
import { config } from '@/config';
import { ResponseUtil } from '@/utils/response';

/**
 * Swagger 文档中间件
 */
export const swaggerDocs = koaSwagger({
  routePrefix: config.swagger.path,
  swaggerOptions: {
    spec: swaggerSpec,
    ...swaggerUiOptions.swaggerOptions,
  } as any,
  title: swaggerUiOptions.customSiteTitle,
  hideTopbar: true,
  favicon: '/favicon-32x32.png',
});

/**
 * Swagger JSON 端点中间件
 */
export const swaggerJson = async (ctx: Context, next: Next): Promise<void> => {
  if (ctx.path === '/api-docs.json' || ctx.path === '/swagger.json') {
    ctx.status = 200;
    ctx.type = 'application/json';
    ctx.body = swaggerSpec;
    return;
  }
  
  await next();
};

/**
 * API 文档重定向中间件
 */
export const apiDocsRedirect = async (ctx: Context, next: Next): Promise<void> => {
  if (ctx.path === '/docs' || ctx.path === '/documentation') {
    ctx.redirect(config.swagger.path);
    return;
  }
  
  await next();
};

/**
 * Swagger 功能检查中间件
 */
export const swaggerFeatureCheck = async (ctx: Context, next: Next): Promise<void> => {
  // 在生产环境中禁用 Swagger（可选）
  if (!config.swagger.enabled) {
    if (ctx.path.startsWith(config.swagger.path) || 
        ctx.path === '/api-docs.json' || 
        ctx.path === '/swagger.json') {
      ctx.status = 404;
      ctx.body = ResponseUtil.notFound('API 文档在当前环境中不可用');
      return;
    }
  }
  
  await next();
};

/**
 * 初始化 Swagger 中间件
 */
export const initializeSwagger = () => {
  const middlewares = [];
  
  // 功能检查
  middlewares.push(swaggerFeatureCheck);
  
  // 重定向
  middlewares.push(apiDocsRedirect);
  
  // JSON 端点
  middlewares.push(swaggerJson);
  
  // 如果启用了 Swagger
  if (config.swagger.enabled) {
    middlewares.push(swaggerDocs);
  }
  
  return middlewares;
};

export default {
  swaggerDocs,
  swaggerJson,
  apiDocsRedirect,
  swaggerFeatureCheck,
  initializeSwagger,
};